package com.um.jdy.app.baofu.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.um.jdy.app.baofu.manager.BaofuRefundManager;
import com.um.jdy.app.charge.manager.EBOrderManager;
import com.um.jdy.app.charge.manager.EVOrderManager;
import com.um.jdy.app.charge.manager.PBOrderManager;
import com.um.jdy.app.user.manager.MonthCardManager;
import com.um.jdy.app.user.manager.WalletManager;
import com.um.jdy.baofu.config.BFConfig;
import com.um.jdy.baofu.config.BaofuPayConfig;
import com.um.jdy.baofu.entity.account.NotifyDataEntity;
import com.um.jdy.baofu.entity.account.ReciveEntity;
import com.um.jdy.baofu.entity.pay.ResultMasterEntity;
import com.um.jdy.baofu.rsa.JHSignatureUtils;
import com.um.jdy.baofu.rsa.RsaCodingUtil;
import com.um.jdy.baofu.utils.RequestParmUtil;
import com.um.jdy.baofu.utils.SecurityUtil;
import com.um.springboot.starter.annotation.TokenRequired;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * 宝付消息接收类
 */
@Api(tags = "宝付消息接收类")
@RestController
@RequestMapping("/api/v1/cms/baofu/receiveNotice")
@Validated
@Slf4j
public class BaofuReceiveNoticeController  {
    @Autowired
    private BFConfig bFConfig;
    @Autowired
    private BaofuPayConfig  baofuPayConfig;
    @Autowired
    private EBOrderManager ebOrderManager;
    @Autowired
    private MonthCardManager monthCardManager;
    @Autowired
    private EVOrderManager evOrderManager;

    @Autowired
    private PBOrderManager pbOrderManager;
    @Autowired
    private  WalletManager walletManager;

    @Autowired
    private BaofuRefundManager baofuRefundManager;


    @PostMapping("payReceiveNotice/{type}/{comId}")
    @ApiOperation(value = "宝付支付回调", notes = "宝付支付回调")
    public String payReceiveNotice(HttpServletRequest request,@PathVariable String type,@PathVariable String comId)  {
        try {
            System.out.println(comId);
            System.out.println(type);
            request.setCharacterEncoding("utf-8");//utf-8编码接收
            RequestParmUtil.getParamLog(request);//打印接收参数

            String  cerpath = baofuPayConfig.getCerpath();//宝付公钥

            Map<String,String> RDateArry = new TreeMap<String,String>();
            Enumeration<String> e = request.getParameterNames();
            while(e.hasMoreElements()) {
                String paraStr = e.nextElement();
                if(paraStr != null){
                    RDateArry.put(paraStr, request.getParameter(paraStr));//接收参数,（使用TreeMap自动排序）
                }
            }
            if(RDateArry.keySet().size()<=0) throw new Exception("参数不存在！");
            ResultMasterEntity rme = JSON.parseObject(JSON.toJSONString(RDateArry),ResultMasterEntity.class);
            log.info("返回参数："+rme);
            if(rme.getSignStr() == null) throw new Exception("缺少验签参数");
            if(rme.getReturnCode().equals("SUCCESS")){
                log.info("11:"+rme.getReturnCode());
                log.info("22:"+rme.getDataContent());
                log.info("33:"+rme.getNotifyType());
                if(JHSignatureUtils.verifySignature(cerpath, rme.getDataContent(), rme.getSignStr())){
                    JSONObject json = JSON.parseObject(rme.getDataContent());
                    String outTradeNo = json.getString("outTradeNo");
                    String tradeNo = json.getString("tradeNo");
                    String finishTime =  json.getString("finishTime");
                    log.info("宝付订单号tradeNo:"+tradeNo);
                    log.info("商户订单号outTradeNo:"+outTradeNo);
                    log.info("支付完成时间finishTime:"+finishTime);

                    //SUCCESS交易成功，支付成功的订单再次发起支付依然返回支付成功，商户侧需做幂等处理
                    //CLOSED已关闭 通常存在3种情况会关闭订单 1：商户侧发起的订单关闭 2：超出订单有效期还未支付成功的订单，系统自动关闭 3：被风控的订单 已关闭的订单不能再次发起支付
                    //WAIT_PAYING下单成功，等待用户支付中
                    //PAY_ERROR支付失败，同一笔订单号在有效期内可再次发起支付
                    //REFUND支付订单已退款
                    //ABNORMAL 支付异常，返回此状态的支付订单，请稍后发起查询。
                    //退款返回状态
                    log.info("订单状态txnState:"+json.getString("txnState"));
                    log.info("成功金额:succAmt"+json.getString("succAmt"));
                    log.info("支付手续费:feeAmt"+json.getString("feeAmt"));
                    log.info("业务结果:feeAmt"+json.getString("resultCode"));
                    log.info("请求渠道订单号:reqChlNo"+json.getString("reqChlNo"));
                        if("PAYMENT".equals(rme.getNotifyType())){//支付
                            String txnState = json.getString("txnState");
                            if("SUCCESS".equals(txnState)) {
                                //月卡支付回调
                                if ("monthCard".equals(type)) {
                                    log.info("月卡支付回调");
                                    monthCardManager.BaofuWxPayNotify(outTradeNo, finishTime, comId);
                                } else if ("chargeEb".equals(type)) {
                                    ///api/v1/order/charge/eb/wxpay/notify/
                                    log.info("Eb支付回调");
                                    ebOrderManager.baofuWxPayNotify(outTradeNo, tradeNo, finishTime);
                                } else if ("chargeEv".equals(type)) {
                                    ///api/v1/order/charge/ev/wxpay/notify/
                                    log.info("Ev支付回调");
                                    evOrderManager.baofuWxPayNotify(outTradeNo, tradeNo, finishTime, comId);
                                } else if ("chargePb".equals(type)) {
                                    ///api/v1/order/charge/pb/deposit/%s/notify/
                                    log.info("pb支付回调");
                                    pbOrderManager.baofuDepositWxPayNotify(outTradeNo, finishTime, comId);
                                } else if ("wallet".equals(type)) {
                                    ///api/v1/user/wallet/wxpay/notify/
                                    log.info("wallet支付回调");
                                    walletManager.baofuWxPayNotify(outTradeNo, finishTime, comId);
                                }
                            }
                        }else if("REFUND".equals(rme.getNotifyType())){//退款
                            String refundState = json.getString("refundState");
                            String msg = json.getString("errMsg");
                            log.info("订单退款状态txnState:"+refundState);
                            log.info("进入退款回调！");
                            if ("monthCard".equals(type)) {
                                log.info("月卡支付回调");
                                baofuRefundManager.cardRefund(outTradeNo, refundState, msg);
                            } else if ("chargeEb".equals(type)) {
                                ///api/v1/order/charge/eb/wxpay/notify/
                                log.info("后台指定退款金额支付回调");
                                baofuRefundManager.chargeEbRefun(outTradeNo, refundState, msg);
                            } else if ("deposit".equals(type)) {
                                ///api/v1/order/charge/ev/wxpay/notify/
                                log.info("deposit回调");
                                baofuRefundManager.depositRefund(outTradeNo, refundState, msg);
                            } else if ("chargePb".equals(type)) {
                                ///api/v1/order/charge/pb/deposit/%s/notify/
                                log.info("pb支付回调");
                                baofuRefundManager.chargePbRefund(outTradeNo, refundState, msg);
                            } else if ("recharge".equals(type)) {
                                ///api/v1/user/wallet/wxpay/notify/
                                log.info("recharge支付回调");
                                baofuRefundManager.rechargeRefund(outTradeNo, refundState, msg);
                            }else if ("wallet".equals(type)) {
                                ///api/v1/user/wallet/wxpay/notify/
                                log.info("wallet支付回调");
                                baofuRefundManager.walletRefund(outTradeNo, refundState, msg);
                            } else if ("chargeEbRefunZd".equals(type)) {
                                ///api/v1/user/wallet/wxpay/notify/
                                log.info("wallet支付回调");
                                baofuRefundManager.chargeEbRefunZd(outTradeNo, refundState, msg);
                            }
                        }
                }else{
                    log.error("验签失败："+rme.toString());
                }
            }else {
                log.error("支付回调失败："+rme.toString());
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "OK";//返回OK与交易状态无关，只表示收到异步通知
    }


}
